using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class RoleInfoWindowOperation : MonoBehaviour
{
	public UISlicedSprite experienceBar;
	public Transform maxbarLength;
	public UILabel experienceLabel;
	public UILabel prestige;
	public UILabel fightValue;
	public UILabel life;
	public UILabel force;
	public UILabel profession;
	public UILabel stunt;
	public UILabel uniqueSkill;
	public UILabel magic;
	public Transform modelPoint;
	public Transform itemParent;
	public Dictionary<int,BackpackItem> backPackItemDic = new Dictionary<int, BackpackItem> ();
	int fightLevelValue;
	int maxExpOfCurrentLevel = 200;
	int exp;
	string[] equipNames = new string[8];
	BackpackItem[] backItems;
	BackpackItem targetItem;
	
	void Awake ()
	{
		backItems = itemParent.GetComponentsInChildren<BackpackItem> ();
		
		UIManagement.Instance ().SetVisiable (gameObject, GameDefine.INVISIABLE);
		
		SendMessageTOServer ();
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_ROLE_OPEN_PANEL_ACK, ListenToServer);
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_EQUIP_TO_BAG_ACK, EquipItemToBack);
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_EQUIP_ITEM_DROP_ACK, DeleteEquip);
		
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_EQUIP_ITEM_INFO_ACK, PopTipsWindow);
		
		
		for (int i = 0; i < backItems.Length; i++) {
			string mName = backItems [i].transform.name;
			int mIndex = int.Parse (mName.Substring (mName.Length - 1));

			backItems [i].index = mIndex;
			
			backPackItemDic.Add (mIndex, backItems [i]);
		}
	}
	
	void SendMessageTOServer ()
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_ROLE_OPEN_PANEL_SYN);
		
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void ListenToServer (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		//解读服务器发来的数据包//
		maxExpOfCurrentLevel = byteArray.readInt ();
		fightLevelValue = byteArray.readInt ();
		
		for (int i = 0; i < equipNames.Length; i++) {
			int equipId = byteArray.readInt ();
			if (equipId != 0)
				equipNames [i] = (int)GameDefine.GameObjectType.GAMEOBJECT_EQUIP + "_" + equipId;
			else {
				equipNames [i] = "";
			}
		}
		
		Init (0);
		
		//PlayerData.Instance ().maxExp = maxExpOfCurrentLevel;
	}
	
	void Start(){
		
		//Hp
		BindManage.getInstance ().BindProp (ModelLocator.getInstance ().scene.Role, "Hp", this, "BindHp");
		
		//武力//
		BindManage.getInstance ().BindProp (ModelLocator.getInstance ().scene.Role, "Str", this, "BindStr");
		
		//Exp
		BindManage.getInstance ().BindProp (ModelLocator.getInstance ().scene.Role, "Exp", this, "BindExp");
		
		BindManage.getInstance ().BindProp (ModelLocator.getInstance ().scene.Role, "Stu", this, "BindStu");
	}
	
	public void Init (int id)
	{	
		UIManagement.Instance ().SetVisiable (gameObject, GameDefine.VISIABLE);
		
		//声望//
		prestige.text = ModelLocator.getInstance ().scene.Role.GetProperties ("Repu").ToString ();
		
		//战斗力//
		fightValue.text = fightLevelValue.ToString ();
		
		//职业//
		string roleId = ModelLocator.getInstance ().scene.Role.GetProperties ("RoleID").ToString ();
		profession.text = BinaryReaderTool.getInstance ().getSwfLangStr ("Role" + roleId);
		
		
		//绝招//
		string skillId = ModelLocator.getInstance ().scene.Role.GetProperties ("SkillID").ToString ();
		string skillName = SqliteReader.getInstance ().getIniVal ("Skill", "SkillID", skillId, new string[]{"Name"}) [0];
		uniqueSkill.text = BinaryReaderTool.getInstance ().getSwfLangStr (skillName);
		
		//法术//
		magic.text = ModelLocator.getInstance ().scene.Role.GetProperties ("Wis").ToString ();
		
		/*
		Debug.Log ("Exp " + ModelLocator.getInstance ().scene.Role.CheckProperties ("Exp"));
		//经验//
		string str = ModelLocator.getInstance ().scene.Role.GetProperties ("Exp").ToString ();
		if (str == "")
			exp = 0;
		else
			exp = int.Parse (str);
		ShowExperienceBar ();
		*/
		
		//模型显示//
		GameObject model = (GameObject)Instantiate (PlayerData.Instance ().MainRoleInstance);
		model.transform.parent = modelPoint.parent;
		model.transform.localPosition = modelPoint.localPosition;
		model.transform.localScale = Vector3.one;
		PlayerAction pa = model.GetComponentInChildren<PlayerAction> ();
		pa.enabled = false;
		
		UILabel nameLabel = model.GetComponentInChildren<UILabel> ();
		nameLabel.enabled = false;
		
		UISprite shadow = model.transform.FindChild ("Shadow").GetComponent<UISprite> ();
		
		shadow.enabled = false;
		
		for (int i = 0; i < equipNames.Length; i++) {
			if (equipNames [i] != "") {
				backPackItemDic [i].icon.enabled = GameDefine.VISIABLE;
				backPackItemDic [i].icon.spriteName = equipNames [i];
				
				backPackItemDic [i].iconBG.enabled = GameDefine.VISIABLE;
				
				backPackItemDic [i].icon.MakePixelPerfect ();
				
				Item item = new Item(equipNames [i],true,false);
				backPackItemDic[i].myItem = item;
			} else {
				backPackItemDic [i].icon.enabled = GameDefine.INVISIABLE;
				backPackItemDic [i].iconBG.enabled = GameDefine.INVISIABLE;
			}
		}
		
		/*
		//s取得当前等级的最大经验值sTODO
		int maxExperience = 10000;
		float maxLength = maxbarLength.localScale.x;
		Vector3 scale = experienceBar.transform.localScale;
		scale.x = maxLength * playerData.Experience / maxExperience;
		experienceBar.transform.localScale = scale;
		experienceLabel.text = GameDefine.EXPERIENCESTRING + playerData.Experience + "/" + maxExperience;
		
		
		
		uniqueSkill.text = playerData.UniqueSkillName();
		magic.text = playerData.MagicName();
		*/
	}
	
		
	//生命//
	public void BindHp (object property, object propertyValue)
	{
		life.text = propertyValue.ToString ();
	}
	
	//武力
	public void BindStr (object property, object propertyValue)
	{
		force.text = propertyValue.ToString ();
	}
	
	public void BindExp (object property, object propertyValue)
	{
		
		Debug.Log("BindExp "+ModelLocator.getInstance ().scene.Role.GetProperties("Exp"));
		//经验显示//
		string expStr = propertyValue.ToString ();
		if (expStr == "")
			exp = 0;
		else
			exp = int.Parse (expStr);
		
		ShowExperienceBar ();
	}
	
	void ShowExperienceBar ()
	{
		float maxLength = maxbarLength.localScale.x;
		Vector3 scale = experienceBar.transform.localScale;
		
		if (PlayerData.Instance ().maxExp == 0)
			PlayerData.Instance ().maxExp = 1;
		scale.x = maxLength * exp / PlayerData.Instance ().maxExp;
		
		if(scale.x == 0f) scale.x = 0.001f;
		
		experienceBar.transform.localScale = scale;
		string lvString = BinaryReaderTool.getInstance ().getSwfLangStr ("String_experience");
		experienceLabel.text = lvString + ":" + exp + "/" + PlayerData.Instance ().maxExp;
	}
	
	public void BindStu (object property, object propertyValue)
	{
		stunt.text = propertyValue.ToString ();
	}
	
	/// <summary>
	/// 移除掉这个事件.
	/// </summary>
	void OnDestroy ()
	{
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_ROLE_OPEN_PANEL_ACK, ListenToServer);
		
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_EQUIP_TO_BAG_ACK);
		
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_EQUIP_ITEM_DROP_ACK);
		
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_EQUIP_ITEM_INFO_ACK);
		
		BindManage.getInstance ().UnbindProp (ModelLocator.getInstance ().scene.Role, "Hp");
		
		BindManage.getInstance ().UnbindProp (ModelLocator.getInstance ().scene.Role, "Str");
		
		BindManage.getInstance ().UnbindProp (ModelLocator.getInstance ().scene.Role, "Exp");
		
		BindManage.getInstance ().UnbindProp (ModelLocator.getInstance ().scene.Role, "Stu");
	}
	
	void DeleteItemRequest (BackpackItem item)
	{
		targetItem = item;
		DeleteItemOperation();
	}
	
	void DeleteItemOperation(){
		UIManagement.Instance ().OpenPopUpWindow ("String_Prompt_discarded", ClickConfirm, ClickCancel);
	}
	
	void MoveOrEquipRequest (BackpackItem item)
	{
		targetItem = item;
		
		//区分装备还是背包物品//
		if (item.targetItem.storageState == BackpackItem.StorageStateType.RoleInfo) {
			//
		} else if (item.targetItem.storageState == BackpackItem.StorageStateType.Backpack) {
			MoveItemToBackpack();
		}
	}
	
	//装备卸下//
	void MoveItemToBackpack(){
		
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_EQUIP_TO_BAG_SYN);
		if(targetItem.targetItem != null){
			//移动卸下//
			int type = 0;
			byteArray.writeByte ((byte)type);
			byteArray.writeByte ((byte)targetItem.index);
			byteArray.writeByte ((byte)targetItem.targetItem.index);
		} else {
			//按钮卸下//
			int type = 1;
			byteArray.writeByte ((byte)type);
			byteArray.writeByte ((byte)targetItem.index);
		}
		
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	//装备丢弃//
	void ClickConfirm ()
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_EQUIP_ITEM_DROP_SYN);
		byteArray.writeByte ((byte)targetItem.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
	}
	
	void ClickCancel ()
	{
		targetItem.icon.enabled = targetItem.myItem.Visible;
	}
	
	/// <summary>
	/// 将装备卸下//
	/// </summary>
	void EquipItemToBack (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			if (targetItem) {
				if(targetItem.targetItem != null){
					targetItem.myItem.Exchange (targetItem.targetItem.myItem);
					
					targetItem.targetItem.Refresh ();
					targetItem.Refresh ();
					
					targetItem.targetItem = null;
				} else {
					int index = (int)byteArray.readByte ();
					
					GameObject packWindow = UIManagement.Instance().GetWindow("Window_Pack");
					
					if(packWindow != null){
						BackpackOperation operation = packWindow.GetComponent<BackpackOperation>();
						
						if(operation != null){
							BackpackItem item =  operation.backPackItemDic[index];
							
							targetItem.myItem.Exchange (item.myItem);
					
							item.Refresh ();
							targetItem.Refresh ();
						}
					}
				}
			}
		} else {
			targetItem.targetItem.Refresh ();
			targetItem.Refresh ();
		}
		
		Cursor.Clear ();
		
		targetItem.canDrop = false;
	}
	
	//丢弃装备//
	void DeleteEquip (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			targetItem.myItem.Visible = false;
			
			targetItem.Refresh ();
		}
		
		Cursor.Clear ();
		targetItem.icon.enabled = targetItem.myItem.Visible;
		
		targetItem.canDrop = false;
	}
	
	//Tips弹窗请求//
	void PopTipsWindowRequest (BackpackItem item)
	{
		ByteArrayEx byteArray = new ByteArrayEx ();
		byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_EQUIP_ITEM_INFO_SYN);
		byteArray.writeByte ((byte)item.index);
		MySocket.getInstance ().Async_Send (byteArray.byteArray);
		
		targetItem = item;
	}
	
	//Tips弹窗//
	void PopTipsWindow (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		byte itemType = byteArray.readByte ();
		int itemId = byteArray.readInt ();
	
		if (itemType == (byte)GameDefine.GameObjectType.GAMEOBJECT_ITEM) {
			//弹物品Tips//
		} else if (itemType == (byte)GameDefine.GameObjectType.GAMEOBJECT_EQUIP) {
			//弹装备Tips//
			Hashtable tipsTable = new Hashtable ();
			string[] equipProperties = SqliteReader.getInstance ().getIniVal ("Equip", "EquipID", itemId.ToString (), new string[]{"Name","Profession","LvLimit"});
			string titleName = BinaryReaderTool.getInstance ().getSwfLangStr (equipProperties [0]);
			string iconSpriteName = targetItem.icon.spriteName;
			tipsTable.Add ("TitleName", titleName);
			tipsTable.Add ("SpriteName", iconSpriteName);
			tipsTable.Add ("EquipProfession", equipProperties [1]);
			tipsTable.Add ("LvLimit", equipProperties [2]);
			Vector3 pos = targetItem.transform.position;
			tipsTable.Add ("EquipPosition", pos);
			
			if(UIManagement.Instance().CheckWindowExits("Window_Pack")){
				string leftStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_unload");
				string rightStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_discarded");
				UIManagement.Instance ().OpenEquipTipsWindow (tipsTable, MoveItemToBackpack, DeleteItemOperation,leftStr,rightStr);
			} else {
				string rightStr = BinaryReaderTool.getInstance ().getSwfLangStr ("String_discarded");
				UIManagement.Instance ().OpenEquipTipsWindow (tipsTable,null,DeleteItemOperation,null,rightStr);
			}
		}
	}
}
